function M = findFace3(Img)
%FINDFACE3 Vrati oblast, ve ktere se nachazi oblicej

Img = im2double(Img);
Img = lightBalance(Img);
[x0 y0] = findCenter(Img);

% vyber oblasti
q = quantile(Img(:), 0.6);
M1 = Img >= q;
M1 = imerode(M1, strel('disk', 2));
cc = bwconncomp(M1, 4);
stats = regionprops(cc, 'area','BoundingBox','ConvexImage','ConvexArea','Centroid');
Cond2 = [stats.Area] ./ [stats.ConvexArea] > 0.25;
n = length(stats);
Distxy = ([stats.Centroid] - repmat([x0 y0], 1, n)) .^ 2;
Dist = round(sqrt(1.5 * Distxy(1:2:(2*n)) + Distxy(2:2:(2*n))));
maxdist = min(Dist);
if maxdist < 50
    maxdist = 50;
Cond3 = Dist <= maxdist;
cidx = find(Cond2 & Cond3);

% sjednoceni vybranych oblasti (doplnenych na konvexni mnozinu)
M2 = zeros(size(Img));
for i = 1:length(cidx)
    comp = stats(cidx(i));
    xc = round(comp.BoundingBox(1));
    xw = comp.BoundingBox(3);
    yc = round(comp.BoundingBox(2));
    yw = comp.BoundingBox(4);
    M2(yc:(yc+yw-1), xc:(xc+xw-1)) = M2(yc:(yc+yw-1), xc:(xc+xw-1)) | comp.ConvexImage;
end

% uzavreni + doplneni na konvexni mnozinu
M2 = imgClose(M2, 20);
cc = bwconncomp(M2, 8);
stats = regionprops(cc, 'BoundingBox','ConvexImage');
M = zeros(size(M2));
for i = 1:length(stats)
    comp = stats(i);
    xc = round(comp.BoundingBox(1));
    xw = comp.BoundingBox(3);
    yc = round(comp.BoundingBox(2));
    yw = comp.BoundingBox(4);
    M(yc:(yc+yw-1), xc:(xc+xw-1)) = M(yc:(yc+yw-1), xc:(xc+xw-1)) | comp.ConvexImage;
end

end

